import { FC, useEffect, Suspense } from 'react';
import { useNavigate, useLocation, useRoutes } from 'react-router-dom';
import { getCookie } from '@/utils/cookie';
import { routes } from './config/menuConfig';

const Route: FC = () => {
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    const user = getCookie().username;

    if (user) {
      if (location.pathname === '/sign_in') {
        navigate('/kc');
      }
    } else {
      navigate('/sign_in');
    }
  }, [location.pathname]);

  const routes_map = (data: any) => {
    return data.map((item: any) => {
      const obj = { ...item };
      if (obj.lazy) {
        obj.element = (
          <Suspense fallback={<h1>loading</h1>}>
            <obj.component />
          </Suspense>
        );
      } else {
        obj.element = <obj.component {...(obj.componentProps || {})} />;
      }

      if (obj.children) {
        obj.children = routes_map(obj.children);
      }
      return obj;
    });
  };

  return useRoutes(routes_map(routes));
};

export default Route;
